package jp.michi.makimono;

import android.util.Log;

public class AsyncRunner implements Runnable {
    protected Thread mThread;
    protected Runnable mNext;
    public void start() {
        Log.v("AsyncRunner", "start");
        interrupt();
        mThread = new Thread(this);
        mThread.setDaemon(true);
        mThread.start();
    }
    public void interrupt() {
        Log.v("AsyncRunner", "interrupt");
        if (mThread != null) {
            mThread.interrupt();
        }
    }
    public void enqueue(Runnable next) {
        synchronized (this) {
            mNext = next;
            notifyAll();
        }
    }
    protected Runnable dequeue() throws InterruptedException {
        synchronized (this) {
            while (mNext == null) {
                wait();
            }
            Runnable o = mNext;
            mNext = null;
            return o;
        }
    }
    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                dequeue().run();
            }
        } catch (InterruptedException e) {
            Log.v("AsyncRunner", "terminate");
        }
    }
}
